﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using SQLServerHealthCheck.Model;


namespace SQLServerHealthCheck.SQLServer
{


    class WMIQueries
    {
        HealthCheckDataContext dc;


        public void GetCPU(PerfServer Server, Time Time, HealthCheckDataContext dc)
        {
            ConnectionOptions connectoptions = new ConnectionOptions();
            connectoptions.Username = Server.Username;
            connectoptions.Password = Server.Password;
            ManagementScope scope = new ManagementScope(@"\\" + Server.Name + @"\root\cimv2", connectoptions);


            ObjectQuery wql = new ObjectQuery("SELECT *   FROM Win32_PerfFormattedData_PerfOS_Processor  WHERE Name <> '_Total'  ");
            ManagementObjectSearcher searcher;
            ManagementObjectCollection results = null;
            try
            {
                searcher = new ManagementObjectSearcher(scope, wql);
                results = searcher.Get();
            }
            catch (Exception e)
            {
                if (e.Message == "User credentials cannot be used for local connections ")
                {
                    searcher = new ManagementObjectSearcher(wql);
                    results = searcher.Get();
                }
            }
            if (results != null)
            {
                foreach (ManagementObject result in results)
                {
                    CpuCore core;
                    var newCore = from a in dc.CpuCores
                                  where a.Name == result["Name"].ToString() && a.PerfServer == Server
                                  select a;
                    if (newCore.Count() == 0)
                    {

                        core = new CpuCore();
                        core.Name = result["Name"].ToString();
                        core.PerfServer = Server;
                        dc.CpuCores.InsertOnSubmit(core);
                    }
                    else
                    {
                        core = newCore.First();
                    }
                    CpuUsage CpuUsage = new CpuUsage();
                    CpuUsage.Time = Time;
                    CpuUsage.CpuCore = core;
                    CpuUsage.Percentage = Convert.ToInt32(result["PercentProcessorTime"]);
                    dc.CpuUsages.InsertOnSubmit(CpuUsage);
                    dc.SubmitChanges();

                }
            }
        }


        public void GetDisk(PerfServer Server, Time Time, HealthCheckDataContext dc)
        {
            ConnectionOptions connectoptions = new ConnectionOptions();
            connectoptions.Username = Server.Username;
            connectoptions.Password = Server.Password;
            ManagementScope scope = new ManagementScope(@"\\" + Server.Name + @"\root\cimv2", connectoptions);


            ObjectQuery wql = new ObjectQuery("SELECT *  from Win32_PerfFormattedData_PerfDisk_PhysicalDisk   ");
            ManagementObjectSearcher searcher;
            ManagementObjectCollection results = null;
            try
            {
                searcher = new ManagementObjectSearcher(scope, wql);
                results = searcher.Get();
            }
            catch (Exception e)
            {
                if (e.Message == "User credentials cannot be used for local connections ")
                {
                    searcher = new ManagementObjectSearcher(wql);
                    results = searcher.Get();
                }
            }
            if (results != null)
            {
                foreach (ManagementObject result in results)
                {
                    if (result["Name"].ToString() != "_Total")
                    {
                        Disk Disk;
                        var newdisk = from a in dc.Disks
                                      where a.name == result["Name"].ToString() && a.PerfServer == Server
                                      select a;
                        if (newdisk.Count() == 0)
                        {

                            Disk = new Disk();
                            Disk.name = result["Name"].ToString();
                            Disk.PerfServer = Server;
                            dc.Disks.InsertOnSubmit(Disk);
                        }
                        else
                        {
                            Disk = newdisk.First();
                        }
                        DiskIO DiskIO = new DiskIO();
                        DiskIO.Time = Time;
                        DiskIO.Disk = Disk;
                        DiskIO.AvgDiskSecPerRead = Convert.ToInt32(result["AvgDiskSecPerRead"]);
                        DiskIO.AvgDiskSecPerWrite = Convert.ToInt32(result["AvgDiskSecPerWrite"]);

                        DiskIO.DiskReadsPerSec = Convert.ToInt32(result["DiskReadsPerSec"]);
                        DiskIO.DiskWritesPerSec = Convert.ToInt32(result["DiskWritesPerSec"]);

                        DiskIO.CurrentDiskQueueLength = Convert.ToInt32(result["CurrentDiskQueueLength"]);

                        dc.DiskIOs.InsertOnSubmit(DiskIO);
                        dc.SubmitChanges();
                    }
                }
            }

        }

    }

}